<template>
  <div>
    <Drawer
      title="新增患者"
      v-model="drawer"
      width="900"
      :mask-closable="false"
      :styles="styles"
      @on-close="closeDrawer('params')"
    >
      <Form
        v-if="loading"
        :model="params"
        label-position="top"
        ref="params"
        :rules="ruleValidate"
      >
        <Row :gutter="32">
          <Col span="6">
            <FormItem label="姓名">
              <Input v-model="params.user_name" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="性别">
              <RadioGroup v-model="params.gender">
                <Radio label="1">男</Radio>
                <Radio label="2">女</Radio>
                <Radio label="0">不详</Radio>
              </RadioGroup>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="年龄" prop="age">
              <InputNumber
                @on-change="changeage(params.age)"
                :min="1"
                :max="150"
                v-model="params.age"
                placeholder="请输入"
              ></InputNumber>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="32">
          <Col span="6" v-for="(item, index) in params.mobile" :key="index">
            <FormItem
              :label="
                params.mobile.length === 1 ? '手机号' : `手机号${index + 1}`
              "
              :prop="'mobile.' + index + '.mobile'"
              :rules="{
                required: +index === 0 ? false : true,
                message: '请输入正确的联系号码',
                pattern: /^\d{10,12}$/,
                trigger: 'blur',
              }"
            >
              <Row type="flex" :gutter="8" justify="start">
                <Col>
                  <Input
                    v-model="item.mobile"
                    placeholder="请输入"
                    @on-keyup="
                      item.mobile = item.mobile.replace(/\s+|[\r\n]/g, '')
                    "
                    @on-blur="telrepeat(item.mobile)"
                    v-width="
                      +index === 0
                        ? +index === params.mobile.length - 1
                          ? 140
                          : 180
                        : +index === params.mobile.length - 1
                        ? 100
                        : 140
                    "
                  ></Input>
                </Col>
                <Col v-if="+index === params.mobile.length - 1">
                  <Button icon="md-add" @click="addmobile"></Button>
                </Col>
                <Col v-if="+index !== 0">
                  <Button
                    ghost
                    type="error"
                    @click="closemobile(index)"
                    icon="md-close"
                  ></Button>
                </Col>
                <Col>
                  <div
                    style="color:#ff9900;font-size:18px"
                    v-if="patientStatus"
                  >
                    ！老患者到诊
                  </div>
                </Col>
              </Row>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="微信号">
              <Input
                v-model="wxFriendInfo.friend_wechatno"
                @on-keyup="
                  params.wechat_id = params.wechat_id.replace(/\s+|[\r\n]/g, '')
                "
                @on-blur="WXrepeat(params.wechat_id)"
                placeholder="请输入"
                disabled
              ></Input>
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem label="城市" required>
              <!-- <Select v-model="params.city_id" placeholder="请输入城市拼音简写" filterable remote clearable
                            :remote-method="remoteMethod" :loading="loadingcity">
                            <Option v-for="item in optionscity" :key="item.value" :value="item.key" :label="item.label"></Option>
                        </Select> -->
              <jgcheckcity
                ref="checkcity"
                v-model="city_id"
                @cityvalue="cityvalue"
                :name="`editPatient${params.id}`"
              ></jgcheckcity>
            </FormItem>
          </Col>
          <Col span="12">
            <Row type="flex" :gutter="32">
              <Col span="12">
                <FormItem label="一级病种" prop="patient_diseases_id">
                  <Select
                    v-model="params.patient_diseases_id"
                    clearable
                    placeholder="请选择"
                    @on-change="changediseases(params.patient_diseases_id)"
                  >
                    <Option
                      v-for="item in diseases"
                      :disabled="+item.status === 0"
                      :value="item.value"
                      :key="item.value"
                      >{{ item.label }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>
              <Col
                span="12"
                v-show="params.patient_diseases_id"
                v-if="diseases_child.length > 0"
              >
                <FormItem label="二级病种" prop="patient_diseases_child_id">
                  <Select
                    v-model="params.patient_diseases_child_id"
                    clearable
                    placeholder="请选择"
                  >
                    <Option
                      v-for="item in diseases_child"
                      :disabled="+item.status === 0"
                      :value="item.value"
                      :key="item.value"
                      >{{ item.label }}</Option
                    >
                  </Select>
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col span="6">
            <FormItem label="归属人" prop="belong_member_id">
              <Select
                disabled
                v-if="+params.is_share === 1 && +params.source_type !== 1"
                v-model="params.belong_member_id"
                placeholder="请选择"
              >
                <Option
                  v-for="item in member"
                  :disabled="+item.status === 0 || +item.is_share === 1"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
              <Select
                :disabled="+is_edit_belong_member === 0"
                v-else
                v-model="params.belong_member_id"
                placeholder="请选择"
              >
                <Option
                  v-for="item in member"
                  :disabled="+item.status === 0 || +item.is_share === 1"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="对话方式" prop="dialog_mode_id">
              <Select
                v-model="params.dialog_mode_id"
                clearable
                placeholder="请选择"
                @on-change="changedialog"
              >
                <Option
                  v-for="item in talk_way"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.label }}
                </Option>
              </Select>
            </FormItem>
          </Col>

          <Col span="6">
            <FormItem label="来源备注" prop="source_remark">
              <Input
                v-model="params.source_remark"
                placeholder="请输入"
              ></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem
              label="部位"
              prop="body_parts_ids"
              v-show="+params.patient_diseases_id === 1"
              v-if="+params.patient_diseases_id === 1"
            >
              <TreeSelect
                :max-tag-count="3"
                v-model="params.body_parts_ids"
                :data="contlist"
                filterable
                multiple
              ></TreeSelect>
            </FormItem>
            <FormItem label="部位" v-show="+params.patient_diseases_id !== 1">
              <TreeSelect
                :max-tag-count="3"
                v-model="params.body_parts_ids"
                :data="contlist"
                filterable
                multiple
              ></TreeSelect>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="患者状态" prop="patient_status_id">
              <Select
                v-model="params.patient_status_id"
                :disabled="
                  +params.patient_status_id === 4 ||
                    (+params.patient_status_id === 5 && is_select)
                "
              >
                <Option
                  :disabled="+item.is_select === 0"
                  v-for="item in patient_status"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.label }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="12" v-if="+params.patient_status_id === 1">
            <Row :gutter="16">
              <Col span="12">
                <FormItem label="预到时间" required>
                  <InputNumber
                    :formatter="$inputday"
                    :step="1"
                    v-model.number="returnVisitDays"
                    @on-change="blurday(returnVisitDays, 1)"
                  >
                  </InputNumber>
                  <span class="ivu-ml-8">天后</span>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label=" ">
                  <DatePicker
                    :editable="false"
                    :options="optionss"
                    type="date"
                    v-model="params.appointment_time"
                    @on-change="changeday(params.appointment_time, 1)"
                    placeholder="请选择预到时间"
                  >
                  </DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Col>
          <Col
            span="12"
            v-if="
              +params.patient_status_id === 1 ||
                +params.patient_status_id === 2 ||
                +params.patient_status_id === 33 ||
                +params.patient_status_id === 39 ||
                +params.patient_status_id === 42
            "
          >
            <Row :gutter="16">
              <Col span="12">
                <FormItem label="下次回访时间" required>
                  <InputNumber
                    :formatter="$inputday"
                    :step="1"
                    v-model.number="returnVisitDay"
                    @on-change="blurday(returnVisitDay, 2)"
                  >
                  </InputNumber>
                  <span class="ivu-ml-8">天后</span>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="回访日期" prop="next_callback_time">
                  <DatePicker
                    :editable="false"
                    :options="optionss"
                    type="date"
                    v-model="params.next_callback_time"
                    @on-change="changeday(params.next_callback_time, 2)"
                    placeholder="请选择下次回访时间"
                  >
                  </DatePicker>
                </FormItem>
              </Col>
            </Row>
          </Col>
        </Row>
      </Form>
      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px;" @click="closeDrawer('params')"
          >取消</Button
        >
        <Button
          type="primary"
          :loading="remarksloading"
          :disabled="disabled"
          @click="handleDrawers('params')"
          >保存</Button
        >
      </div>
    </Drawer>
  </div>
</template>
<script>
// import jgcheckcity from '@/components/checkcity';
import { mapActions, mapGetters, mapMutations, mapState } from "vuex";
import {
  patientindexeditinfo,
  patientindexsearchchildchannel,
  patientindexcreate,
  patientindexinfo,
  patientindexsearchchilddiseases,
  patientindexsearchmobile,
  repeatbaiyou,
} from "@/api/hqapi";
import { PatientList, WxFriend, RetrunVisit } from "@/api/chat";
import dayjs from "dayjs";
export default {
  name: "DetailEdit",
  components: {  },
  data() {
    return {
      city_id: [],
      loading: true,
      drawer: false,
      remarksloading: false,
      edit: "",
      returnVisitDay: null,
      returnVisitDays: null,
      disabled: false,
      childchannelshow: true,
      styles: {
        height: "calc(100% - 55px)",
        overflow: "auto",
        paddingBottom: "53px",
        position: "static",
      },
      dialog: "",
      ruleValidate: {
        body_parts_ids: [
          {
            required: true,
            message: "请选择部位",
            type: "array",
            trigger: "change",
          },
        ],
        age: [
          {
            required: true,
            message: "请填写年龄",
            type: "number",
            trigger: "blur,change",
          },
        ],
        belong_member_id: [
          {
            required: true,
            message: "请选择归属人",
            trigger: "change",
          },
        ],
        patient_status_id: [
          {
            required: true,
            message: "请选择患者状态",
            trigger: "change",
          },
        ],
        patient_diseases_id: [
          {
            required: true,
            message: "请选择一级病种",
            trigger: "change",
          },
        ],
        patient_diseases_child_id: [
          {
            required: true,
            message: "请选择二级病种",
            trigger: "change",
          },
        ],
        dialog_mode_id: [
          {
            required: true,
            message: "请选择对话方式",
            trigger: "change",
          },
        ],
        source_remark: [
          {
            required: true,
            message: "请输入来源备注",
            trigger: "blur",
          },
        ],
        city_id: [
          {
            required: true,
            message: "请选择城市",
            type: "string",
            trigger: "change",
          },
        ],
        next_callback_time: [
          {
            required: true,
            message: "请选择回访日期",
            type: "date",
            trigger: "change",
          },
        ],
      },
      mobilelist: [{}, {}],
      params: {
        id: 0,
        user_name: "",
        is_share: undefined,
        source_type: undefined,
        gender: "",
        birthday: "",
        age: null,
        mobile: [],
        wechat_id: "",
        patient_diseases_id: "",
        patient_diseases_child_id: "",
        belong_member_id: "",
        dialog_mode_id: "",
        source_remark: "",
        body_parts_ids: [],
        patient_status_id: "",
        profession: "",
        is_genetic_history: "",
        marital_status: "",
        is_pregnancy: "",
        city_id: [],
        address: "",
        appointment_time: "",
        next_callback_time: "",
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now();
        },
      },
      optionss: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 24 * 3600 * 1000;
        },
      },
      contlist: [],
      diseases: [],
      diseases_child: [],
      member: [],
      patient_status: [],
      talk_way: [],
      city: "",
      labelPosition: "left",
      bool: false,
      source_channellist: [],
      child_source_channel: [],
      is_edit_belong_member: "", // 是否有归属人修改权限
      is_select: true,
      patientStatus: false, // 是否老患者到诊状态
      id: "",
    };
  },
  computed: {
    ...mapState("chatwebsocket/wechat", [
      "wxFriendInfo",
      "realname",
      "patientList",
      "covItem",
      "currentWechat",
      "patientList",
    ]),
  },

  methods: {
    ...mapMutations("chatwebsocket/wechat", [
      "setReturnVisit",
      "setPatientList",
      "setWxFriendInfo",
    ]),
    initial() {
      this.editinfo(0);
      this.drawer = true;
    },
    cityvalue(city) {
      this.city_id = city;
      this.params.city_id = city;
    },
    handleOpenDrawer() {
      (this.params = {
        id: 0,
        user_name: "",
        is_share: undefined,
        source_type: undefined,
        gender: "",
        birthday: "",
        age: null,
        qq: "",
        dy_num: "",
        mobile: [],
        wechat_id: "",
        patient_diseases_id: "",
        patient_diseases_child_id: "",
        belong_member_id: "",
        dialog_mode_id: "",
        source_remark: "",
        body_parts_ids: [],
        patient_status_id: "",
        remark: "",
        profession: "",
        is_genetic_history: "",
        marital_status: "",
        is_pregnancy: "",
        city_id: [],
        address: "",
        appointment_time: "",
        next_callback_time: "",
        channel_id: "",
        subdivided_channels_id: "",
      }),
        this.$refs.params.resetFields();
      this.editinfo(0);
    },
    editinfo(id) {
      this.loading = false;
      this.params.id = id;
      patientindexeditinfo({ id: id }).then((res) => {
        if (id === 0) this.edit = true;
        else this.edit = false;
        // if(+res.patient_data_type !== 0) this.bool = true;
        // else this.bool = false;
        this.drawer = true;
        this.params.user_name = res.user_name;
        this.params.gender = res.gender;
        this.params.birthday = res.birthday;
        this.params.age = res.age || null;
        this.params.qq = res.qq;
        this.params.dy_num = res.dy_num;
        this.params.mobile = [];
        this.is_edit_belong_member = res.is_edit_belong_member;
        for (let index in res.mobile) {
          this.params.mobile.push({
            mobile: res.mobile[index],
          });
        }
        if (+this.params.mobile.length === 0) {
          this.params.mobile = [
            {
              mobile: "",
            },
          ];
        }
        this.params.wechat_id = res.wechat_id;
        this.params.patient_diseases_id = res.patient_diseases_id;
        this.params.patient_diseases_child_id =
          res.patient_diseases_child_id === "0"
            ? ""
            : res.patient_diseases_child_id;
        this.params.belong_member_id = this.params.belong_member_id
          ? ""
          : this.params.belong_member_id;
        this.params.dialog_mode_id = res.dialog_mode_id + "";
        this.params.source_remark = res.source_remark;
        this.params.body_parts_ids = res.body_parts_ids;
        this.params.patient_status_id = res.patient_status_id + "";
        this.params.remark = res.remark;
        this.params.profession = res.profession;
        this.params.is_genetic_history = res.is_genetic_history + "";
        this.params.marital_status = res.marital_status + "";
        this.params.is_pregnancy = res.is_pregnancy + "";
        this.city_id = [
          res.province_id ? res.province_id : "",
          res.city_id ? res.city_id : "",
          res.area_id ? res.area_id : "",
        ];
        this.params.city_id = [
          res.province_id ? res.province_id : "",
          res.city_id ? res.city_id : "",
          res.area_id ? res.area_id : "",
        ];
        this.params.address = res.address;
        this.params.appointment_time = res.appointment_time;
        this.params.next_callback_time = res.next_callback_time;
        this.params.channel_id = res.channel_id == 0 ? "" : res.channel_id + "";
        this.params.subdivided_channels_id =
          res.subdivided_channels_id == 0
            ? ""
            : res.subdivided_channels_id + "";
        this.contlist = res.condition.body_parts;
        this.diseases = res.condition.diseases;
        this.source_channellist = res.condition.source_channel;
        this.child_source_channel = res.condition.child_source_channel;
        this.diseases_child = res.condition.diseases_child;
        // this.member = res.condition.member
        this.member = [];
        if (+this.params.is_share === 1 && +this.params.source_type !== 1) {
          this.member.push({
            value: res.belong_member_id,
            label: res.belong_member_name,
          });
        } else {
          for (let item of res.condition.member) {
            this.member.push(...item.children);
          }
        }
        this.patient_status = res.condition.patient_status;
        for (let item of this.patient_status) {
          if (item.label === "老患者到诊") {
            this.is_select = +item.is_select === 0;
          }
        }
        this.talk_way = res.condition.talk_way;
        this.changedialog(res.dialog_mode_id);
        if (this.params.appointment_time)
          this.changeday(this.params.appointment_time, 1);
        if (this.params.next_callback_time)
          this.changeday(this.params.next_callback_time, 2);
        this.loading = true;
      });
    },
    closeDrawer(name) {
      if (name) {
        this.$refs[name].resetFields();
        this.patientStatus = false;
      }

      this.returnVisitDay = null;
      this.returnVisitDays = null;
      this.drawer = false;
    },
    handleDrawers(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.remarksloading = true;
          this.disabled = true;
          let mobiles = [];
          for (let item of this.params.mobile) {
            mobiles.push(item.mobile);
          }
          let config = JSON.parse(JSON.stringify(this.params));
          config.body_parts_ids = config.body_parts_ids.join(",");
          config.mobile = mobiles.join(",");
          config.city_id = config.city_id.join(",");
          config.wechat_id = this.wxFriendInfo.friend_wechatno;
          patientindexcreate(config)
            .then(() => {
              this.$Message.success("新增成功");
              // 获取患者列表
              this.getPatientList(this.covItem);
              // 获取好友信息
              this.getWxFriendInfo(this.covItem);
              this.drawer = false;
              this.remarksloading = false;
              this.disabled = false;
              this.returnVisitDay = null;
              this.returnVisitDays = null;
            })
            .catch(() => {
              this.remarksloading = false;
              this.disabled = false;
            });
          // this.$refs.copytable.initial(params);
          // this.submithuanzhe();
        }
      });
    },
    getPatientList(covItem) {
      console.log(covItem, "getPatientList");
      PatientList({
        wechatid: covItem.wechatid,
        friendid: covItem.friendid,
        accountid: this.currentWechat.accountid,
      }).then((res) => {
        console.log(res, "getPatientList");
        this.setPatientList(res.list);
        // 获取微聊回访记录
        this.getReturnVisit(covItem);
      });
    },
    getReturnVisit(covItem) {
      if (!this.patientList.length) return;
      console.log("this.patientList[0].id", this.patientList);
      console.log("this.patientList[0].id", this.patientList[0].id);
      RetrunVisit({
        patient_user_id: this.patientList[0].id,
        wechatid: covItem.wechatid,
        friendid: covItem.friendid,
      }).then((res) => {
        this.setReturnVisit(res.list);
      });
    },
    getWxFriendInfo(covItem) {
      WxFriend({
        wechatid: covItem.wechatid,
        friendid: covItem.friendid,
      }).then((res) => {
        this.setWxFriendInfo(res);
      });
    },
    telrepeat(data) {
      let config = {
        // data_type: 2,
        // type: 0,
        id: this.params.id === undefined ? 0 : this.params.id,
        mobile: data,
      };
      patientindexsearchmobile(config).then((res) => {
        if (res.result === 1) {
          this.$Message.warning({
            duration: 2.5,
            content: "该手机号码已存在",
          });
        }
      });
      repeatbaiyou({ mobile: data }).then((res) => {
        // console.log(res,'res')
        this.patientStatus = res;
      });
    },
    WXrepeat(data) {
      let config = {
        // data_type: 2,
        // type: 0,
        id: this.params.id === undefined ? 0 : this.params.id,
        wechat_id: data,
      };

      patientindexsearchmobile(config).then((res) => {
        if (res.result === 2) {
          this.$Message.warning({
            duration: 2.5,
            content: "该微信号已存在",
          });
        }
      });
    },
    changedialog(e) {
      this.talk_way.forEach((item) => {
        if (+item.value === +e) this.dialog = item.label;
      });
    },
    changediseases(pid) {
      patientindexsearchchilddiseases({
        pid: pid,
        patient_user_id: this.id,
      }).then((res) => {
        this.diseases_child = res.list;
        this.params.patient_diseases_child_id = "";
      });
    },
    blurday(num, type) {
      if (type === 1) this.params.appointment_time = this.$blurday(num);
      else if (type === 2) this.params.next_callback_time = this.$blurday(num);
    },
    changeday(date, type) {
      if (type === 1) this.returnVisitDays = this.$changeday(date);
      else if (type === 2) this.returnVisitDay = this.$changeday(date);
    },
    changebirthday(birthday) {
      this.params.age = dayjs().$y - dayjs(birthday).$y || 1;
    },
    changeage(age) {
      let year = dayjs().$y - age;
      this.params.birthday = `${year}-01-01`;
    },
    addmobile() {
      if (+this.params.mobile.length < 5) {
        this.params.mobile.push({
          mobile: "",
        });
      } else {
        this.$Message.warning("手机号最多添加5个");
      }
    },
    closemobile(index) {
      this.params.mobile.splice(index, 1);
    },
    changechannel(id) {
      this.child_source_channel = [];
      this.params.subdivided_channels_id = "";
      patientindexsearchchildchannel({ pid: id }).then((res) => {
        this.child_source_channel = res.list;
      });
    },
  },
};
</script>
<style scoped>
.u-tit {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}
</style>
